<template>
<div class="dashboard-container">
    <div class="dashboard-date">
        <a-range-picker v-model:value="rangeDate" :placeholder="['开始时间','结束时间']" @change="selectDateChange" :locale='locale' mod='date' />
        <a-button type="primary" class='add-btn' @click="showModal">
            <template #icon>
                <PlusSquareTwoTone />
            </template>
            新增记录
        </a-button>
    </div>
    <a-row>
        <a-col :span='6'>
            <a-card>
                <a-statistic :title='stockObj.title' :value='stockObj.value' :precision="2" suffix="¥" :value-style="{ color: stockObj.color }" style="margin-right: 50px">
                    <template #prefix>
                        <arrow-up-outlined v-if="stockObj.upOrDownStatus === 'up'" />
                        <arrow-down-outlined v-if="stockObj.upOrDownStatus === 'down'" />
                    </template>
                </a-statistic>
            </a-card>
        </a-col>
        <a-col :span='6'>
            <a-card>
                <a-statistic :title='fundObj.title' :value='fundObj.value' :precision="2" suffix="¥" :value-style="{ color: fundObj.color }" style="margin-right: 50px">
                    <template #prefix>
                        <arrow-up-outlined v-if="fundObj.upOrDownStatus === 'up'" />
                        <arrow-down-outlined v-if="fundObj.upOrDownStatus === 'down'" />
                    </template>
                </a-statistic>
            </a-card>
        </a-col>
        <a-col :span='6'>
            <a-card>
                <a-statistic :title='goldObj.title' :value='goldObj.value' :precision="2" suffix="¥" :value-style="{ color: goldObj.color }" style="margin-right: 50px">
                    <template #prefix>
                        <arrow-up-outlined v-if="goldObj.upOrDownStatus === 'up'" />
                        <arrow-down-outlined v-if="goldObj.upOrDownStatus === 'down'" />
                    </template>
                </a-statistic>
            </a-card>
        </a-col>
        <a-col :span='6'>
            <a-card>
                <a-statistic :title='totalObj.title' :value='totalObj.value' :precision="2" suffix="¥" :value-style="{ color: totalObj.color }" style="margin-right: 50px">
                    <template #prefix>
                        <arrow-up-outlined v-if="totalObj.upOrDownStatus === 'up'" />
                        <arrow-down-outlined v-if="totalObj.upOrDownStatus === 'down'" />
                    </template>
                </a-statistic>
            </a-card>
        </a-col>
    </a-row>
    <div id='myChart' :style="echartsStyle"></div>
    <a-button type="link" class="login_out" @click="loginOutEvent">退出登录</a-button>
    <div class="username_container">
        <UserOutlined />
        <span class='username_container_text'>{{username}}</span>
    </div>
    <a-layout-footer style="text-align: center;position:fixed;bottom:0;width:100%;">
    <a href="http://beian.miit.gov.cn">渝ICP备2021002299号-1</a>
    </a-layout-footer>
    <!-- 新增模态框 -->
    <a-modal v-model:visible="visibleModal" title="新增收益" @ok="handleOk" @cancel="handleCancel">
        <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" ref="formRef" :rules="rules">
            <a-form-item label="日期" name='date'>
                <a-date-picker v-model:value="formState.date" @change="changeModalDate" type="date" placeholder="日期" style="width: 100%" />
            </a-form-item>
            <a-form-item label="股票">
                <a-input v-model:value="formState.stock" type='number' placeholder="-100为浮亏100,100为浮盈100" />
            </a-form-item>
            <a-form-item label="基金">
                <a-input v-model:value="formState.fund" type='number' placeholder="-100为浮亏100,100为浮盈100" />
            </a-form-item>
            <a-form-item label="黄金">
                <a-input v-model:value="formState.gold" type='number' placeholder="-100为浮亏100,100为浮盈100" />
            </a-form-item>
        </a-form>
    </a-modal>
</div>
</template>

<script>
import {
    ref,
    reactive,
    onMounted,
} from 'vue'
import {
    useRouter
} from 'vue-router'
import {
    ArrowUpOutlined,
    ArrowDownOutlined,
    PlusSquareTwoTone,
    UserOutlined

} from '@ant-design/icons-vue';
import service from "@/utils/axios/http";
import tokenEvent from "@/utils/utils";
import * as echarts from 'echarts'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import moment from 'moment';
import 'moment/dist/locale/zh-cn';
moment.locale('zh_cn')
import {
    message
} from 'ant-design-vue';
const {
    loginOut,
    get_username
} = tokenEvent
export default {
    components: {
        ArrowUpOutlined,
        ArrowDownOutlined,
        PlusSquareTwoTone,
        UserOutlined
    },
    setup() {
        let oneDataId = 0; // 数据id
        const formState = reactive({
            date: undefined,
            stock: 0,
            fund: 0,
            gold: 0
        }); // 新增收益对象
        const formRef = ref();
        const router = useRouter()
        const visibleModal = ref(false)
        const echartsStyle = ref({
            width: '100%',
            height: '1000px'
        })
        let rangeDate = ref([]) // 开始结束时间
        const downColor = ref('#3f8600'); // 下跌时颜色;
        const upColor = ref('#cf1322');
        // 股票
        let stockObj = reactive({
            title: '股票',
            value: 0,
            color: upColor,
            upOrDownStatus: 'up'
        })
        // 基金
        let fundObj = reactive({
            title: '基金',
            value: 0,
            color: upColor,
            upOrDownStatus: 'up',
        })
        // 黄金
        let goldObj = reactive({
            title: '黄金',
            value: 0,
            color: upColor,
            upOrDownStatus: 'up',
        })
        // 总结
        let totalObj = reactive({
            title: '总计',
            value: 0,
            color: upColor,
            upOrDownStatus: 'up',
        })
        const getAllData = () => {
            let options = {};
            if (rangeDate.value && rangeDate.value.length > 0) {
                options['rangeDate'] = rangeDate.value;
            }
            service.post('/data/getAllData', options).then((response) => {
                const {
                    data
                } = response;
                if (data.code === 200) {
                    handleHeaderData(data);
                    handleChartsData(data);
                } else {
                    message.error(data.msg || '获取数据失败！')
                }
            }).catch((err) => {
                console.log(err, 'err')
            })
        }
        const handleHeaderData = (data = {}) => {
            const list = data.data || [];
            let totalStock = 0;
            let totalFund = 0;
            let totalGold = 0;
            let totalData = 0;
            list.forEach(element => {
                totalStock += Number(element.stock)
                totalFund += Number(element.fund)
                totalGold += Number(element.gold)
                stockObj.value = totalStock;
                stockObj.color = totalStock > 0 ? upColor : downColor;
                stockObj.upOrDownStatus = totalStock > 0 ? 'up' : 'down';
                fundObj.value = totalFund;
                fundObj.color = totalFund > 0 ? upColor : downColor;
                fundObj.upOrDownStatus = totalFund > 0 ? 'up' : 'down';
                goldObj.value = totalGold;
                goldObj.color = totalGold > 0 ? upColor : downColor;
                goldObj.upOrDownStatus = totalGold > 0 ? 'up' : 'down';

            });
            totalData = (Number(stockObj.value) + Number(fundObj.value) + Number(goldObj.value))
            totalObj.value = totalData;
            totalObj.color = totalData > 0 ? upColor : downColor;
            totalObj.upOrDownStatus = totalData > 0 ? 'up' : 'down';

        }
        const handleChartsData = (data) => {
            let xData = [];
            let yData = [];
            let stockArr = [];
            let fundArr = [];
            let goldArr = [];
            let totalArr = [];
            let list = data.data || [];
            list.forEach(element => {
                xData.push(element.date);
                stockArr.push(element.stock)
                fundArr.push(element.fund)
                goldArr.push(element.gold)
                totalArr.push((Number(element.gold) + Number(element.stock) + Number(element.fund)).toFixed(2))
            })
            yData = [{
                    name: '股票',
                    type: 'line',
                    stack: '总计',
                    data: stockArr,
                    smooth: true
                },
                {
                    name: '基金',
                    type: 'line',
                    stack: '总计',
                    data: fundArr,
                    smooth: true

                },
                {
                    name: '黄金',
                    type: 'line',
                    stack: '总计',
                    data: goldArr,
                    smooth: true

                },
                {
                    name: '总计',
                    type: 'line',
                    stack: '总计',
                    data: totalArr,
                    smooth: true
                },
            ]
            let myChart = echarts.init(document.getElementById('myChart'));
            const options = {
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'category',
                    data: xData
                },
                yAxis: {
                    type: 'value'
                },
                series: yData
            }
            myChart.setOption(options)
        }
        onMounted(getAllData)

        // 时间改变时间
        const selectDateChange = () => {
            getAllData()
        }
        const loginOutEvent = () => {
            router.push('/login')
            loginOut()
        }
        const showModal = () => {
            visibleModal.value = true;
        }
        const handleOk = () => {
            const {
                date = '',
                    stock = 0,
                    fund = 0,
                    gold = 0,
            } = formState;
            formRef.value
                .validate()
                .then(() => {
                    if (oneDataId) {
                        service.post('/data/updateData', {
                            date,
                            stock,
                            fund,
                            gold,
                            dataId:oneDataId
                        }).then((res) => {
                            const {
                                data: {
                                    code,
                                    msg = ''
                                }
                            } = res
                            visibleModal.value = false;
                            formState.date = undefined;
                            formState.stock = 0;
                            formState.fund = 0;
                            formState.gold = 0;
                            if (code === 200) {
                                message.success('操作成功');
                                getAllData()
                            } else {
                                message.error(msg || '操作失败');
                            }
                        }).catch((error) => {
                            console.log(error)
                        })
                    } else {
                        service.post('/data/addData', {
                            date,
                            stock,
                            fund,
                            gold
                        }).then((res) => {
                            const {
                                data: {
                                    code,
                                    msg = ''
                                }
                            } = res
                            visibleModal.value = false;
                            formState.date = undefined;
                            formState.stock = 0;
                            formState.fund = 0;
                            formState.gold = 0;
                            if (code === 200) {
                                message.success('操作成功');
                                getAllData()
                            } else {
                                message.error(msg || '操作失败');
                            }
                        }).catch((error) => {
                            console.log(error)
                        })
                    }

                })
                .catch(error => {
                    console.log('error', error);
                });
        }
        const handleCancel = () => {
            formState.date = undefined;
            formState.stock = 0;
            formState.fund = 0;
            formState.gold = 0;
        }
        const rules = {
            date: [{
                required: true,
                message: 'Please pick a date',
                trigger: 'change',
                type: 'object'
            }],
        };
        const changeModalDate = () => {
            if (formState.date) {
                service.post('/data/getDateByDate', {
                    date: formState.date,
                }).then((res) => {
                    const {
                        data: {
                            code,
                            msg = '',
                            data = []
                        }
                    } = res
                    const {
                        date,
                        stock,
                        fund,
                        gold,
                        dataId = 0,
                    } = data[0]
                    oneDataId = dataId;
                    if (code === 200) {
                        console.log(stock,gold,fund)
                        formState.date = formState.date;
                        formState.stock = stock;
                        formState.fund = fund;
                        formState.gold = gold;
                    } else {
                        formState.date = formState.date;
                        formState.stock = 0;
                        formState.fund = 0;
                        formState.gold = 0;
                    }
                }).catch((err) => {
                    formState.date = formState.date;
                    formState.stock = 0;
                    formState.fund = 0;
                    formState.gold = 0;
                })
            }

        }
        return {
            rangeDate,
            stockObj,
            fundObj,
            goldObj,
            totalObj,
            selectDateChange,
            echartsStyle,
            loginOutEvent,

            visibleModal,
            showModal,
            formState,
            labelCol: {
                span: 4,
            },
            wrapperCol: {
                span: 14,
            },
            rules,
            formRef,
            handleOk,
            handleCancel,
            locale,
            moment,

            username: get_username(),

            changeModalDate,
        }
    }
}
</script>

<style lang="less" scoped>
// 内部样式
.ant-card-bordered {
    border: none;
}

// 自定义样式
.dashboard-container {
    padding: 5vh 2vw;
    position: relative;

    .login_out {
        position: absolute;
        top: 0;
        right: 0;
    }

    .add-btn {
        float: right;
    }

    .username_container {
        position: absolute;
        top: 0.3vh;
        right: 4vw;

        &_text {
            margin-left: .3vw;
            vertical-align: middle;
        }
    }

    .dashboard-date {}
}
</style>
